package com.wxproj.wxai.webSocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.Claim;
import com.wxproj.wxai.entity.UserText;
import com.wxproj.wxai.utils.AiManager;
import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;

import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.*;

import java.util.Date;

import static com.wxproj.wxai.utils.AiManager.STABLE_TEMPERATURE;


public class TestSocketHandler implements WebSocketHandler {

    @Resource
    private AiManager aiManager;
    private final static Logger LOGGER = LoggerFactory.getLogger(TestSocketHandler.class);

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        LOGGER.info("Test Socket 连接成功，sessionId：{}", session.getId());
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        if (message instanceof TextMessage) {
            handlerTextMessage(session, (TextMessage) message);
        } else {
            LOGGER.error("Test Socket 消息处理失败，只接受 文本消息，sessionId：{}", session.getId());
        }
    }

    public void handlerTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        final String msg = message.getPayload();
        final String token = msg.split("///token")[1];
        final String content = msg.split("///token")[0];
        if (token!=null) {
            Flowable vals = aiManager.doStreamRequest("小言",content,STABLE_TEMPERATURE);
            Flowable<String> mappedFlowable = vals.map(item -> "Number: " + item);
            StringBuffer val = new StringBuffer();
            // 订阅并处理数据
            mappedFlowable.subscribeOn(Schedulers.io())
                    .observeOn(Schedulers.single())
                    .subscribe(
                            item -> {
                                session.sendMessage(new TextMessage(item));
                                String head = item.split("\"content\":\"")[1];
                                String body = head.split("\"}}]")[0];
                                val.append(body);
                                System.out.println(body);
                            }, // onNext
                            error -> error.printStackTrace(),  // onError
                            () -> {
                                session.sendMessage(new TextMessage("current_done"));
                                System.out.println(val.toString());
                                Claim claim = JWT.decode(token).getClaim("id");
                                String id = claim.toString().replaceAll("\"","");
                                UserText userText = new UserText();
                                userText.setContent(val.toString());
                                userText.setUser_id(id);
                                userText.setCreate_time(new Date());
                                aiManager.addText(userText);
                            }  // onComplete
                    );
            LOGGER.info("Test Socket 收到消息：{}", msg);
        } else {
            session.sendMessage(new TextMessage("token is null用户未登录"));
        }

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        LOGGER.error("Test Socket 处理异常，sessionId：{}, 异常原因：{}", session.getId(), exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        LOGGER.info("Test Socket 关闭，sessionId：{}", session.getId());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}